package cc.aiee.demo.springboot.core;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cc.aiee.core.bean.R;
import cc.aiee.core.enums.ErrCodeEnum;

@RestControllerAdvice
public class GlobalExceptionControllerAdvice {
	
	@ExceptionHandler(value = { MethodArgumentNotValidException.class, BindException.class })
	@ResponseStatus(value = HttpStatus.BAD_REQUEST)
	public R<Map<String, String>> handleVaildException(Exception e) {
		BindingResult bindingResult = null;
		if (e instanceof MethodArgumentNotValidException) {
			bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
		} else if (e instanceof BindException) {
			bindingResult = ((BindException) e).getBindingResult();
		}
		Map<String, String> errorMap = new HashMap<>(16);
		bindingResult.getFieldErrors()
				.forEach((fieldError) -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
		return new R<>(ErrCodeEnum.e_param_valid_400, errorMap);
	}

}
